import { login, getProfile, getUserDetailById } from '@/api/user'
// Cookies
import { getToken, setToken, removeToken } from '@/utils/auth'

import router from '@/router'
// 状态
const state = {
  // 设置token共享状态
  // token: ''
  // 刷新页面时，先看看本地储存有没有备份
  // token: localStorage.getItem('token') || ''
  token: getToken() || '',
  profile: {}
}
// 修改状态
const mutations = {
  setToken(state, data) {
    // 每当将token存入vuex的时候, 同时存一份到本地储存
    // localStorage.setItem('token', data)
    setToken(data)
    state.token = data
  },
  setProfile(state, data) {
    state.profile = data
  },
  removeToken(state) {
    removeToken()
    state.token = ''
  },
  removProfile(state) {
    state.profile = {}
  }

}
// 执行异步
const actions = {
  async login(store, data) {
    // 登录页应该将用户填入手机号和密码作为data传入
    const res = await login(data)
    console.log('调用接口之后')
    // store.commit('setToken', res.data.dat)
    store.commit('setToken', res)
    // 登录成功记录token的同时要记录时间戳, 用以主动介入token超时判断
    localStorage.setItem('loginTime', Date.now())
  },
  async getProfile(store) {
    const res = await getProfile()
    // store.commit('setProfile', res)
    const datail = await getUserDetailById(res.userId)
    store.commit('setProfile', {
      ...res,
      ...datail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    router.push('login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

